var express = require('express');
var jwt = require('jsonwebtoken'); //用来生产token
var router = express.Router();
const connection = require('../mysql/mysql');
const transport = require('../utils/sendEmail');


/* 登录 */
router.post('/login', function (req, res, next) {
  let data = req.body;
  for (let v in data) {
    if (!data[v]) {
      return res.json({
        code: 1,
        data: null,
        success: false,
        message: v == 'name' ? '用户名不能为空' : '密码不能为空',
      })
    }
  }
  const sql = `SELECT * FROM b_user WHERE name = '${data.name}'`;
  connection.query(sql, (err, result) => {
    if (err) {
      return res.json({
        code: 1,
        data: null,
        success: false,
        message: '失败',
      })
    }
    if (result.length == 0) {
      return res.json({
        code: 1,
        data: null,
        success: false,
        message: '用户名不存在',
      })
    }
    let userInfo = result[0];

    if (userInfo.password != data.password) {
      return res.json({
        code: 1,
        data: null,
        success: false,
        message: '密码错误',
      })
    }

    let content = {name: data.name};
    let secretOrPrivateKey = "jwt";// 这是加密的key（密钥）
    let token = jwt.sign(content, secretOrPrivateKey, {
      expiresIn: 60 * 60 * 4  // 1小时过期
    });

    req.session.user = userInfo;

    res.json({
      code: 0,
      data: {
        token: token,
        userInfo: {
          name: userInfo.name,
          role: userInfo.role
        }
      },
      success: true,
      message: '登录成功',
    })
  });
});

/* 退出登录 */
router.get('/logout', function (req, res, next) {
  let token = req.headers.token;
  if (token) {
    //校验token
    jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
      if (err) {   //如果token过期则会执行err的代码块
        return res.json({
          code: 5,
          data: null,
          success: false,
          message: '退出登录失败！',
        });
      }
      req.session.user = null;
      return res.json({
        code: 0,
        data: null,
        success: true,
        message: '退出登录成功！',
      })
    })
  }
});

/* 查询文章列表 */
router.post('/queryAdminArticleList', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }

    let param = req.body;
    let startPage = (Number(param.pageNum) - 1) * param.pageSize;
    let sql = "";
    let sqlTotal = "";
    if (param.classify) {
      sql = `SELECT * FROM b_article WHERE classify = '${param.classify}' ORDER BY createTime DESC LIMIT ${startPage}, ${Number(param.pageSize)}`;
      sqlTotal = `SELECT COUNT(*) FROM b_article WHERE classify = '${param.classify}'`;
    } else {
      sql = `SELECT * FROM b_article ORDER BY createTime DESC LIMIT ${startPage}, ${Number(param.pageSize)}`;
      sqlTotal = `SELECT COUNT(*) FROM b_article`;
    }
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: '查询失败',
        })
      }
      result.forEach(item => {
        item.tags = item.tags.split(';');
      });
      connection.query(sqlTotal, (err1, result1) => {
        let total = result1[0]['COUNT(*)'];
        res.json({
          code: 0,
          data: {
            rows: result,
            total: Number(total)
          },
          success: true,
          message: '查询成功',
        })
      });
    });

  });
});

/* 设置文章是否可见 */
router.post('/updateArticleIsShow', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }

    let param = req.body;
    for (let v in param) {
      if (!param[v] && param[v] != 0) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: v + '值不能为空',
        })
      }
    }

    let sql = `UPDATE b_article SET isShow = ${param.isShow} WHERE id = ${param.id}`;
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: false,
          success: false,
          message: '修改失败',
        })
      }
      res.json({
        code: 0,
        data: true,
        success: true,
        message: '修改成功',
      })
    });

  });
});

/* 创建文章 */
router.post('/createArticle', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: err,
        success: false,
        message: '登录过期',
      });
    }

    let param = req.body;

    for (let v in param) {
      if (v != 'id' && !param[v] && param[v] != 0) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: v + '值不能为空',
        })
      }
    }
    let tags = '';
    if (param.tags.length > 0) {
      tags = param.tags.join(';');
    }
    let sql = `INSERT INTO b_article (id, classify, tags, title, author, msgs, view, content, imgPath, isShow, description) VALUES (${null},'${param.classify}','${tags}','${param.title}','旭东','${param.msgs}','${param.view}','${param.content}','${param.imgPath}','${param.isShow}','${param.description}')`;
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: err,
          success: false,
          message: '创建失败',
        })
      }
      res.json({
        code: 0,
        data: true,
        success: true,
        message: '创建成功',
      })
    });

  });
});

/* 修改文章详情 */
router.post('/updateArticleDetail', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }

    let param = req.body;
    if (!param.id) {
      return res.json({
        code: 1,
        data: null,
        success: false,
        message: 'id不能为空',
      })
    }

    for (let v in param) {
      if (!param[v] && param[v] != 0) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: v + '值不能为空',
        })
      }
    }
    let tags = '';
    if (param.tags.length > 0) {
      tags = param.tags.join(';');
    }
    let sql = `UPDATE b_article SET title = '${param.title}', description = '${param.description}', content = '${param.content}', author = '旭东', classify = '${param.classify}', tags = '${tags}', isShow = ${param.isShow}, imgPath = '${param.imgPath}' WHERE id = ${param.id}`;
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: false,
          success: false,
          message: '修改失败',
        })
      }
      res.json({
        code: 0,
        data: true,
        success: true,
        message: '修改成功',
      })
    });

  });
});

/* 删除文章 */
router.post('/deleteArticle', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }

    let param = req.body;
    if (!param.id) {
      return res.json({
        code: 1,
        data: null,
        success: false,
        message: 'id不能为空',
      })
    }
    let sql = `DELETE FROM b_article WHERE id = ${param.id}`;
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: false,
          success: false,
          message: '删除失败',
        })
      }
      res.json({
        code: 0,
        data: true,
        success: true,
        message: '删除成功',
      })
    });

  });
});

/* 根据id查询文章详情 */
router.get('/queryAdminArticleDetail', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }
    let id = req.query.id;
    if (!id) {
      return res.json({
        code: 1,
        data: null,
        success: false,
        message: 'id不能为空',
      })
    }
    const sql = `SELECT * FROM b_article WHERE id = '${id}'`;
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: '查询失败',
        })
      }
      result[0].tags = result[0].tags.split(';');
      res.json({
        code: 0,
        data: result[0],
        success: true,
        message: '查询成功',
      })
    });
  });
});

/* 查询classify列表 */
router.get('/queryAdminClassifyList', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }
    const sql = "SELECT * FROM b_classify";
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: '查询失败',
        })
      }
      res.json({
        code: 0,
        data: result,
        success: true,
        message: '查询成功',
      })
    });
  });
});

/* 创建轮播图 */
router.post('/addAndUpdateSlide', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  let param = req.body;
  if (param.isUpdate) {
    for (let v in param) {
      if ((v == 'id' || v == 'title' || v == 'imgPath') && !param[v]) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: v + '值不能为空',
        })
      }
    }
  } else {
    for (let v in param) {
      if ((v == 'title' || v == 'imgPath') && !param[v]) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: v + '值不能为空',
        })
      }
    }
  }

  let sql = "";
  if (param.isUpdate) {
    sql = `UPDATE b_slide SET title = '${param.title}', description = '${param.description}', imgPath = '${param.imgPath}', webPath = '${param.webPath}', isShow = ${param.isShow} WHERE id = ${param.id}`;
  } else {
    sql = `INSERT INTO b_slide (id, title, description, imgPath, webPath, isShow) VALUES (${null},'${param.title}','${param.description}','${param.imgPath}','${param.webPath}',${param.isShow})`;
  }
  connection.query(sql, (err, result) => {
    if (err) {
      return res.json({
        code: 1,
        data: err,
        success: false,
        message: '保存失败',
      })
    }
    res.json({
      code: 0,
      data: true,
      success: true,
      message: '保存成功',
    })
  });
});

/* 删除轮播图 */
router.post('/deleteSlide', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }

    let param = req.body;
    if (!param.id) {
      return res.json({
        code: 1,
        data: null,
        success: false,
        message: 'id不能为空',
      })
    }
    let sql = `DELETE FROM b_slide WHERE id = ${param.id}`;
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: err,
          success: false,
          message: '删除失败',
        })
      }
      res.json({
        code: 0,
        data: null,
        success: true,
        message: '删除成功',
      })
    });

  });
});

/* 设置轮播图是否可见 */
router.post('/updateSlideIsShow', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }

    let param = req.body;
    for (let v in param) {
      if (!param[v] && param[v] != 0) {
        return res.json({
          code: 1,
          data: null,
          success: false,
          message: v + '值不能为空',
        })
      }
    }

    let sql = `UPDATE b_slide SET isShow = ${param.isShow} WHERE id = ${param.id}`;
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: err,
          success: false,
          message: '修改失败',
        })
      }
      res.json({
        code: 0,
        data: null,
        success: true,
        message: '修改成功',
      })
    });

  });
});

/* 查询轮播图列表 */
router.post('/queryAdminSlideList', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  //校验token
  jwt.verify(token, 'jwt', function (err, decoded) { // decoded:指的是tokne解码后用户信息
    if (err) {   //如果token过期则会执行err的代码块
      return res.json({
        code: 5,
        data: null,
        success: false,
        message: '登录过期',
      });
    }

    let param = req.body;
    let startPage = (Number(param.pageNum) - 1) * param.pageSize;
    let sql = `SELECT * FROM b_slide ORDER BY createTime DESC LIMIT ${startPage}, ${Number(param.pageSize)}`;
    let sqlTotal = `SELECT COUNT(*) FROM b_slide`;
    connection.query(sql, (err, result) => {
      if (err) {
        return res.json({
          code: 1,
          data: err,
          success: false,
          message: '查询失败',
        })
      }
      connection.query(sqlTotal, (err1, result1) => {
        let total = result1[0]['COUNT(*)'];
        res.json({
          code: 0,
          data: {
            rows: result,
            total: Number(total)
          },
          success: true,
          message: '查询成功',
        })
      });
    });

  });
});

/* 发送邮件 */
router.post('/sendEmail', function (req, res, next) {
  let param = req.body;

  const sql = `SELECT * FROM b_user_info WHERE id = ${Number(param.byAiteId)}`;
  connection.query(sql, (err, result) => {
    if (err) {
      return res.json({
        code: 1,
        data: err,
        success: false,
        message: '发送失败',
      })
    }

    let mailOptions = {
      from: '291652928@qq.com', // 发件地址
      to: result[0].email, // 收件列表
      subject: `${param.subject}，您好！收到来自东的回复`, // 标题
      text: "",
      html: `<span>@${param.subject}：</span>${param.content}` // html 内容
    };

    transport.sendMail(mailOptions, function (err, response) {
      if (err) {
        res.json({
          code: 1,
          data: err,
          success: false,
          message: '发送失败',
        });
        transport.close();
        return
      }
      res.json({
        code: 0,
        data: null,
        success: true,
        message: '发送成功',
      });
      transport.close();
    });

  });
});

/* 删除评论 */
router.post('/deleteComment', function (req, res, next) {
  let param = req.body;
  if (!param.id) {
    return res.json({
      code: 1,
      data: null,
      success: false,
      message: 'id不能为空',
    })
  }
  let sql = `DELETE FROM b_comment WHERE id = ${param.id} or targetId = ${param.id}`;

  connection.query(sql, (err, result) => {
    console.log(result)
    if (err) {
      return res.json({
        code: 1,
        data: err,
        success: false,
        message: '删除失败',
      })
    }
    res.json({
      code: 0,
      data: null,
      success: true,
      message: '删除成功',
    })
  });
});

/* 创建和修改标签 */
router.post('/addAndUpdateTag', function (req, res, next) {
  let token = req.headers.token;
  if (!token) {
    return res.json({
      code: 5,
      data: null,
      success: false,
      message: '未登录',
    });
  }
  let param = req.body;
  if (!param.tag) {
    return res.json({
      code: 1,
      data: null,
      success: false,
      message: 'tag值不能为空',
    })
  }

  let sql = "";
  if (param.id == 0 || param.id) {
    sql = `UPDATE b_tag SET tag = '${param.tag}' WHERE id = ${param.id}`;
  } else {
    sql = `INSERT INTO b_tag (id, tag) VALUES (${null},'${param.tag}')`;
  }
  connection.query(sql, (err, result) => {
    if (err) {
      return res.json({
        code: 1,
        data: err,
        success: false,
        message: '保存失败',
      })
    }
    res.json({
      code: 0,
      data: true,
      success: true,
      message: '保存成功',
    })
  });
});

module.exports = router;
